package com.infra.micro.quartz.domain.core;

import com.infra.common.util.ThreadPoolUtils;
import com.infra.micro.quartz.domain.config.BizConfig;
import com.infra.micro.quartz.domain.entity.QuartzJobLogPO;
import com.infra.micro.quartz.domain.service.QuartzJobLogService;
import com.infra.micro.quartz.domain.service.impl.JobAlarm;
import com.infra.micro.quartz.model.vo.QuartzJobVO;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.PersistJobDataAfterExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.net.InetAddress;
import java.util.Date;

/**
 * 禁止并发执行
 *
 * @author PD
 */
@SuppressWarnings("unchecked")
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class QuartzJobExecutor extends QuartzJobBean {
    private static final Logger LOGGER = LoggerFactory.getLogger(QuartzJobExecutor.class);
    private static final String RUN_METHOD_NAME = "run";
    @Resource
    private BizConfig bizConfig;
    @Resource
    private QuartzJobLogService quartzJobLogService;

    @Override
    protected void executeInternal(JobExecutionContext context) {
        QuartzJobVO quartzJobVO = (QuartzJobVO) context.getMergedJobDataMap()
                .get(QuartzJobVO.JOB_KEY);

        //构建执行日志对象
        QuartzJobLogPO quartzJobLogPO = buildQuartzJobLogPO(quartzJobVO);

        //任务开始时间
        long startTime = System.currentTimeMillis();

        try {
            LOGGER.info("任务准备执行，任务ID：" + quartzJobVO.getJobId());

            // 执行任务结果
            String taskResult = (String) ThreadPoolUtils.getTaskResult(ThreadPoolUtils.submit(new QuartzJobCallable(quartzJobVO.getBeanName(), RUN_METHOD_NAME, quartzJobVO.getParams())));
            if (bizConfig.isQuartzSaveExecuteResult()) {
                quartzJobLogPO.setResult(taskResult);
            }

            //总时长
            quartzJobLogPO.setTimes(System.currentTimeMillis() - startTime);
            //任务状态
            quartzJobLogPO.setIsSucceed(true);

            LOGGER.info("任务执行完毕，任务ID: {}  总共耗时: {} 毫秒", quartzJobVO.getJobId(), quartzJobLogPO.getTimes());
        } catch (Exception e) {
            LOGGER.error("任务执行失败，任务ID: {}", quartzJobVO.getJobId(), e);
            //总时长
            quartzJobLogPO.setTimes(System.currentTimeMillis() - startTime);
            //任务状态
            quartzJobLogPO.setIsSucceed(false);
            quartzJobLogPO.setResult(((InvocationTargetException) e.getCause()).getTargetException().getMessage());

        } finally {
            quartzJobLogService.insert(quartzJobLogPO);
            ThreadPoolUtils.submit(() -> {
                try {
                    SpringContextBean.getBean(JobAlarm.class).send(quartzJobVO, quartzJobLogPO);
                } catch (Exception e) {
                    LOGGER.error("发送预警信息时出现异常", e);
                }
            });
        }
    }

    /**
     * 构建QuartzJobLogPO持久化对象
     *
     * @param QuartzJobVO
     * @return
     */
    public static QuartzJobLogPO buildQuartzJobLogPO(QuartzJobVO QuartzJobVO) {
        QuartzJobLogPO result = new QuartzJobLogPO();

        result.setJobId(QuartzJobVO.getJobId());
        result.setBeanName(QuartzJobVO.getBeanName());
        result.setParams(QuartzJobVO.getParams());
        result.setCreateTime(new Date());
        result.setHostName(getHostName());
        return result;
    }

    public static String getHostName() {
        try {
            InetAddress address = InetAddress.getLocalHost();
            String hostName = address.getHostName();
            String ip = address.getHostAddress();
            return String.format("%s[%s]", hostName, ip);
        } catch (Exception ex) {
            return "null";
        }

    }
}
